/************************************************************************
* font.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"
#include "path.h"
#define _WM_EXPOSE_ALL
#include "wm.h"
#include "graphics.h"
#include "array.h"

#include <string.h>

array_t *fonts = NULL;

/* load a font file */
int font_load(char* file, char* token)
{
	char* t;
	font_t *f;
	int r = 1;
	if (!fonts)
		fonts = array_create(ARRAY_TYPE_PTR);

	if (!file || !token)
		return 0;

	t = strrchr(file,'.');
	if (!t)
		return 0;

	f = malloc(sizeof(font_t));
	f->token = strdup(token);

	t++;

	if (!strcmp(t,"ttf")) {
		r = font_load_ttf(f,file);
	}else{
		vlprintf(CN_ERROR, "Unsupported Font: %s",file);
	}

	if (r) {
		free(f->token);
		free(f);
		return 0;
	}

	array_push_ptr(fonts,f);

	return fonts->length;
}

/* get a font by id */
font_t *font_get(int id)
{
	font_t *f;
	if (!fonts)
		font_load("font.ttf","default");
	if (!fonts)
		return NULL;

	if (id == UI_DEFAULT)
		id = 1;

	f = array_get_ptr(fonts,id-1);
	if (!f)
		f = array_get_ptr(fonts,0);

	return f;
}

/* get a font by token */
font_t *font_find(char* token)
{
	int i;
	font_t **f;
	if (!fonts)
		font_load("font.ttf","default");
	if (!fonts)
		return NULL;

	f = fonts->data;
	for (i=0; i<fonts->length; i++) {
		if (!strcmp(f[i]->token,token))
			return f[i];
	}

	return array_get_ptr(fonts,0);
}

/* get the id of a font */
int font_get_id(char* token)
{
	int i;
	font_t **f;
	if (!fonts)
		font_load("font.ttf","default");
	if (!fonts)
		return 0;

	f = fonts->data;
	for (i=0; i<fonts->length; i++) {
		if (!strcmp(f[i]->token,token))
			return i+1;
	}

	if (!strcmp(token,"default"))
		return 1;

	return 0;
}
